<template>
  <div class="container">
    <div class="head-nav">
      <van-icon
        name="arrow-left"
        color="#fff"
        size="23"
        @click="$global.goBack()"
      />
      <div class="title">MINT</div>
    </div>
    <div class="main">
      <div class="progress">
        <div class="progress-head">
          <div class="label-text">Mint进度：</div>
          <div class="label-text">我的BNB:{{ myAmount }}</div>
        </div>
        <van-progress
          class="progress-dom"
          :percentage="percentage"
          track-color="#fff"
          stroke-width="12"
          :show-pivot="false"
        />
      </div>
      <div class="form-item">
        <div class="label-text">铸造次数：</div>
        <div class="form-input">
          <input
            type="number"
            v-model.number="amount"
            placeholder="请输入铸造次数"
            max="100"
            min="0"
            :oninput="`if(value>${highest})value=${highest};if(value<0)value=0`"
          />
          <div class="all" v-if="myAmount > 0" @click="handleAll">全部</div>
        </div>
        <div class="label-text tip-text">需要支付：{{ payNumber }}BNB</div>
      </div>
      <div class="form-item">
        <div class="label-text">邀请人地址：</div>
        <div class="form-input">
          <input
            type="text"
            v-model.trim="invitersAddress"
            placeholder="请输入邀请人地址"
          />
        </div>
        <div
          class="form-button"
          :class="{ disabled: payDisabled }"
          @click="handlePay"
        >
          MINT
        </div>
      </div>
      <div class="form-item">
        <div class="label-text">推广链接：</div>
        <div class="form-text">
          <!-- <input
            type="text"
            v-model.trim="promotionLink"
            placeholder="请输入推广链接"
          /> -->
          {{ promotionLink }}
        </div>
        <div
          class="form-button"
          :class="{ disabled: promotionLink === '' }"
          @click="handleCopy"
        >
          复制推广链接
        </div>
      </div>
      <div class="tip-item">
        <div class="label-text">MINT说明：</div>
        <p>mint一次{{ money }}BNB，单个钱包最高{{ highest }}次</p>
      </div>
    </div>
    <binding-popup ref="binding" @update="bindingUpdate" />
  </div>
</template>

<script>
import BigNumber from "bignumber.js";
import bindingPopup from "@/components/binding";
import { mapState } from "vuex";
import { sendTransaction, getGasLimit, collection } from "@/utils/web3";
export default {
  components: { bindingPopup },
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Mint",
  computed: {
    ...mapState({
      walletAddress: (state) => state.user.walletAddress,
    }),
    payNumber() {
      return new BigNumber(Number(this.amount)).times(this.money).toNumber();
    },
    payDisabled() {
      return !this.amount;
    },
    percentage() {
      const totaltoken = this.totaltoken || 0;
      return ((Number(totaltoken) / this.percentageMax) * 100).toFixed(2);
    },
  },
  data() {
    return {
      percentageMax: 5450000,
      money: 0.0055,
      highest: 100,
      myAmount: 0,
      totaltoken: 0,
      amount: "",
      invitersAddress: "",
      promotionLink: "",
    };
  },
  async mounted() {
    const isBinding = await this.$store.dispatch("user/getBinding");
    this.invitersAddress = isBinding || this.$route.query?.address || "";
    // if (!isBinding) {
    //   // this.$refs.binding.open();
    // } else {
    //   this.invitersAddress = isBinding || this.$route.query?.address || "";
    // }
    this.promotionLink = `${location.origin}/#/?address=${this.walletAddress}`;

    const totaltoken = await this.$store.dispatch("user/getTotaltoken");
    this.totaltoken = totaltoken;

    const balance = await this.$store.dispatch("user/getBalance");
    this.myAmount = balance;
  },
  methods: {
    async bindingUpdate() {
      const isBinding = await this.$store.dispatch("user/getBinding");
      this.invitersAddress = isBinding;
    },
    /**
     * 全部
     */
    handleAll() {
      const num = new BigNumber(Number(this.myAmount))
        .div(this.money)
        .toNumber();
      this.amount = num > 100 ? 100 : num;
      // console.log(`次数：${num}`);
      // console.log(`我的bnb：${this.myAmount}`);
    },
    /**
     * 支付
     */
    handlePay() {
      // console.log(`需要支付${this.payNumber}bnb`);
      const invitersAddress =
        this.invitersAddress || this.$route.query?.address || "";

      if (this.payNumber > this.myAmount) {
        this.$toast.fail("余额不足");
        return;
      }
      getGasLimit(
        this.walletAddress,
        collection,
        Number(this.payNumber),
        invitersAddress
      )
        .then((gasLimit) => {
          sendTransaction({
            from: this.walletAddress,
            amount: Number(this.payNumber),
            gasLimit,
            invitersAddress,
          })
            .then((res) => {
              if (res.blockHash) {
                this.$toast.success("支付成功");
                this.amount = "";
              }
            })
            // eslint-disable-next-line no-unused-vars
            .catch((error) => {
              this.$toast.fail("支付失败");
            });
        }) // eslint-disable-next-line no-unused-vars
        .catch((error) => {
          this.$toast.fail("支付失败");
        });
    },

    /**
     * 复制
     */
    handleCopy() {
      this.$copyText(this.promotionLink).then(
        () => {
          this.$toast.success("复制成功!");
        },
        () => {
          this.$toast.fail("复制失败!");
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.container {
  background-image: url("./../../assets/images/bg-mint.png");
}
</style>
